<template>
  <div class="app-container">
    <!--    <el-row :gutter="20">-->
    <!-- 列表 -->
    <!--      <el-col :lg="24" :xs="24">-->
    <div class="toolbar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="课程名称"
            clearable
            style="width: 300px;height: 30px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size='large' @click="handleQuery" :icon='Search'
          >搜索</el-button
          >
          <el-button @click="resetQuery" size='large' :icon='Refresh'>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style='margin-bottom: 10px;'>
      <div>
        <el-button
          size='large'
          type="primary"
          :icon='Plus'
          @click="openDialog('user-form')"
        >新增</el-button
        >
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      :strip='true'
      :border='true'
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
<!--      <el-table-column
        key="id"
        label="课程id"
        align="center"
        prop="id"
        width="100"
      />-->
      <el-table-column
        key="categoryId"
        label="课程分类"
        align="center"
        prop="categoryName"
        width="200"
      >
        <template #default="scope">
<!--          {{categoryOptions.filter((c)=>c.value == 3)[0].label}}-->
          {{scope.row.categoryId}}
        </template>
      </el-table-column>
      <el-table-column
        key="name"
        label="课程名称"
        align="center"
        prop="name"
        width="200"
      />
      <el-table-column
        label="已预约人数"
        width="100"
        align="center"
        prop="reserveCnt"
      />
      <el-table-column
        label="课程名额"
        align="center"
        prop="personCnt"
        width="100"
      />
      <el-table-column
        label="课程费用"
        align="center"
        prop="fees"
        width="100"
      />
      <el-table-column
        label="课程费用"
        align="center"
        prop="fees"
        width="100"
      >
        <template #default="scope">
<!--          <el-dialog v-model="showPic">
            <img w-full :src="showPicUrl" alt="预览图片" />
          </el-dialog>-->
          <img style="width: 100px;height: 100px;" :src="scope.row.pic" :alt="scope.row.name" @click="viewPic(scope.row.pic)"/>
        </template>
      </el-table-column>
      <el-table-column
        label="课程简介"
        align="center"
        prop="description"
        width="100"
      >
        <template #default="scope">
          <el-button>查看简介</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        width="150"
        prop="createTime"
      />
      <el-table-column
        label="更新时间"
        align="center"
        width="150"
        prop="updateTime"
      />
      <el-table-column label="操作" align="center" >
        <template #default="scope">
          <el-button
            type="danger"
            size="small"
            @click="openNewTab(scope.row.id)"
            :icon="EditPen"
          >课程安排</el-button>

          <el-button
            type="primary"
            size="small"
            @click="openPlanDialog('user-form', scope.row.id)"
            :icon="Plus"
          >课程计划</el-button>

          <el-button
            type="success"
            size="small"
            @click="openDialog('user-form', scope.row.id)"
            :icon="Edit"
          >编辑</el-button
          >
          <el-button
            type="warning"
            size="small"
            @click="handleDeleteEquipment(scope.row.id)"
            :icon="Delete"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-footer class='footer'>
      <el-pagination
        large
        background
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-count='pagination.pageCount'
        layout='total, prev, pager, next'
        :total='pagination.total'
        class='mt-4'
        style='float: right'
        @change='getPage'
      />
    </el-footer>
    <!--        </el-card>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <!-- 课程计划弹窗 -->
    <el-dialog
      v-model="planDialog.visible"
      :title="planDialog.title"
      :width="planDialog.width"
      append-to-body
      @close="closePlanDialog"
    >
<!--      @click="addCoursePlans"-->
      <div>
        <h3 style="background-color: #f6f0f0">课程名称</h3>
        <el-header>{{planDialog.courseName}}</el-header>
      <el-divider border-style="dashed"></el-divider>
        <h3 style="background-color: #f6f0f0">添加计划</h3>
        <div>
        </div>
        <el-button
          size='small'
          type="primary"
          :icon='Plus'
          @click="addPlanRow(planDialog.courseId)"
        >添加计划</el-button
        >
      <el-table :data="coursePlansTableData" border stripe>
        <el-table-column prop="name" label="计划名称" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.name" size="small"/>
          </template>
        </el-table-column>
        <el-table-column property="description" label="计划描述" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.description" size="small"/>
          </template>
        </el-table-column>
        <el-table-column property="homework" label="课后作业">
          <template #default="scope">
            <el-input v-model="scope.row.homework" size="small"/>
          </template>
        </el-table-column>
        <el-table-column property="step" label="计划步骤">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.step" size="small"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              @click="deletePlanRow(scope.row)"
              :icon="Delete"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      </div>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addCoursePlans">确 定</el-button>
          <el-button @click="closePlanDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="课程分类" prop="status">
          <el-select v-model="formData.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="课程名称" prop="sn">
          <el-input
            v-model="formData.name"
            :disabled="!!formData.id"
            placeholder="请输入场地型号"
          />
        </el-form-item>-->

        <el-form-item label="课程名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input type="number" min="1" v-model="formData.fees" placeholder="请输入设备价格" />
        </el-form-item>
<!--        <el-form-item label="设备价格" prop="price">
          <el-input v-model="formData.price" placeholder="请输入设备价格" />
        </el-form-item>-->
        <el-form-item label="展示图片" prop="pic">
            <el-upload
              v-model:file-list="fileListOne"
              :action="uploadAction"
              ref="uploadImage"
              list-type="picture-card"
              :limit="1"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :on-success="handleSuccess"
              :on-exceed="handleExceed"
              :auto-upload="false"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogOneVisible">
              <img w-full :src="dialogOneImageUrl" alt="预览图片" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="图片集" prop="picSet">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadAction"
            list-type="picture-card"
            :limit="6"
            multiple
            :on-preview="handleMPictureCardPreview"
            :on-success="handleMSuccess"
            :on-remove="handleMRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="课程简介" prop="address">
          <el-input
            type="textarea"
            :autosize="{minRows: 6}"
            clearable
            v-model="formData.description"
            placeholder="请填写简介"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import {
  getCoursePage,
  getCourseForm,
  addCourse,
  updateCourse,
  deleteCourse
} from "@/api/course/list";
import {getAllCategory} from '@/api/course/category'
import {getPlansByCourseId,batchAddCoursePlan,clearCoursePlans} from '@/api/course/plan'
import { Plus, Delete, Edit, Search, Share, Refresh, EditPen } from '@element-plus/icons-vue'
import type { Course, CourseForm, CourseQueryParams, CourseVO } from '@/api/course/list/types.ts'
import { type UploadInstance, ElMessageBox, ElMessage, ElForm, type UploadFile, type UploadFiles } from 'element-plus'
import { ref,onMounted,reactive } from "vue";
import router from '@/router'
import type { UploadProps, UploadUserFile } from 'element-plus'

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<CourseQueryParams>({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<CourseVO[]>(); // 分页数据
const pagination = ref({
  pageNum: 1,pageSize: 10,total: 0,pageCount: 1
});
const uploadAction = '/dev/api/v1/common/upload'

//------------------------------------------------------------------
// const showPic = ref(false)
// const showPicUrl = ref('')
const viewPic = (src: string)=>{
  // showPic.value = true
  // showPicUrl.value = src;
}

//------------------------------------------------------------------

//==================================================================
const fileListOne = ref<UploadUserFile[]>([])
const uploadImage = ref({})
const dialogOneImageUrl = ref('')
const dialogOneVisible = ref(false)
const imgUrl = ref('')
function handleExceed(files: UploadUserFile[]) {
  uploadImage.value.clearFiles();
  const file = files[0];
  uploadImage.value.handleStart(file);
}
const handleRemove = async (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('onremove',uploadFile,uploadFiles);
  console.log('url',uploadFile.response.data);
  uploadImage.value.clearFiles();
  imgUrl.value = ''
  fileListOne.value = [];
  console.log('handleRemove',imgUrl.value);
}
const handlePictureCardPreview = (file: UploadUserFile) => {

}
const handleChange = (file,fileList) =>{
  uploadImage.value.submit()
}
const handleSuccess = (res,file)=>{
  imgUrl.value = res.data
  console.log('handleOneSuccess',imgUrl.value)
  // fileListOne.value = [file]
}
//==================================================================

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const fileList = ref<UploadUserFile[]>([])
const multiUploadImage = ref(null)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imgUrls = ref([])
const handleMRemove: UploadProps['onRemove'] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  const url = uploadFile.response.data
  console.log('remove',url,imgUrls.value.filter(u=>u !== url),imgUrls.value)
  imgUrls.value = imgUrls.value.filter(u=>u !== url)
  console.log('removed',imgUrls.value)
}

const handleMPictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleMSuccess = (uploadFile: UploadFile, uploadFiles: UploadFiles)=>{
  imgUrls.value.push(uploadFile.data)
  console.log('imgUrls',imgUrls.value);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

const disabled = ref(false);
const planDisabled = ref(false);
// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 弹窗对象
const planDialog = reactive({
  visible: false,
  type: "user-form",
  width: 1000,
  title: "课程信息",
  courseName: '',
  courseId: -1,
});

const categoryOptions = ref([])

// 表单数据
const formData = reactive<CourseForm>({
});


// 校验规则
const rules = reactive({
  name: [{ required: true, message: "课程名不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  getPage(queryParams.pageNum,queryParams.pageSize);
}

function getPage(currentPage:number,pageSize :number){
  pagination.value.currentPage = queryParams.pageNum = currentPage || 1;
  pagination.value.pageSize = queryParams.pageSize = pageSize || 10
  loading.value = true;
  getCoursePage(queryParams)
    .then(({ data }) => {
      pageData.value = data.records;
      total.value = data.total;
      pagination.value.currentPage = data.current
      pagination.value.pageSize = data.size
      pagination.value.total = data.total
      pagination.value.pageCount = data.pages
      queryParams.pageNum = data.current;
      queryParams.pageSize = data.size;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    if (id) {
      dialog.title = "修改课程信息";
      disabled.value = true;
      getCourseForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
    } else {
      dialog.title = "新增课程信息";
    }
  }
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id ID
 */
const courseName = ref<string>('');
const coursePlansTableData = ref([]);
const addPlanRow = (cid) => {
  const newRow = {
    courseId: cid,
    name: null,
    description: null,
    step: null,
    homework: null,
  }
  coursePlansTableData.value.push(newRow);
}
const deletePlanRow = (row) => {
  const index = coursePlansTableData.value.indexOf(row);
  coursePlansTableData.value.splice(index, 1);
}
function openPlanDialog(type: string, id: number) {
  planDialog.visible = true;
  planDialog.type = type;
  planDialog.courseId = id;
  getCourseForm(id).then(({ data }) => {
    planDialog.courseName = data.name;
  });
  getPlansByCourseId(id).then(({ data }) => {
    coursePlansTableData.value = data;
  })
}

function openNewTab(cid?: number) {
  router.push({name: 'course-schedule', state: {cid: cid}})
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    // formData.status = 1;
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closePlanDialog() {
  planDialog.visible = false;
  coursePlansTableData.value.splice(0,coursePlansTableData.value.length);
}

const addCoursePlans = () => {
  if(coursePlansTableData.value && coursePlansTableData.value.length > 0) {
    batchAddCoursePlan(coursePlansTableData.value).then(({ data }) => {

    });
  }else {
    clearCoursePlans(planDialog.courseId).then((res) => {
      if(res.code === '00000') {
        ElMessage.success("操作成功");
      }
    })
  }
  planDialog.visible = false;

}

/** 表单提交 */
const handleSubmit = (() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const id = formData.id;
        console.log('==========================',formData);
        loading.value = true;
        formData.pic = imgUrl.value
        formData.picSet = JSON.stringify(imgUrls.value)
        if (id) {
          updateCourse(formData)
            .then(() => {
              ElMessage.success("修改课程信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          addCourse(formData)
            .then(() => {
              ElMessage.success("新增课程信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 计划表单提交 */
const handlePlanSubmit = (() => {
  if (planDialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const id = formData.id;
        console.log('==========================',formData);
        loading.value = true;
        if (id) {
          updateCourse(formData)
            .then(() => {
              ElMessage.success("修改课程信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          addCourse(formData)
            .then(() => {
              ElMessage.success("新增课程信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 删除 */
function handleDeleteEquipment(id: number) {
  ElMessageBox.confirm("确认删除课程信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteCourse(id).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

function getAllCategoryOptions() {
  getAllCategory().then(({ data }) => {
    if(data && data.length > 0) {
      data.forEach((item: any) => {
        const cid = item.id;
        const cname = item.name;
        categoryOptions.value.push({
          value: cid,
          label: cname
        });
      })
    }
  })
}
// getAllCategoryOptions();
onMounted(() => {
  getAllCategoryOptions();
  handleQuery();
});
</script>
.toolbar {
padding: 10px 0;
}
<style scoped>
.footer {
  margin-top: 20px;
}
</style>
